PEP 448 -- Additional Unpacking Generalizations
https://www.python.org/dev/peps/pep-0448/
Python3.5で新たな文法機能として追加された
https://docs.python.org/ja/3/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations
* イテラブルアンパック演算子と ** 辞書アンパック演算子の利用方法が拡張されました。 関数呼び出し で任意の数のアンパックで使えるようになりました:
同様に、タプル、リスト、集合、辞書表現でも複数のアンパックが使えます
This PEP proposes extended usages of the * iterable unpacking operator and ** dictionary unpacking operators to allow unpacking in more positions, an arbitrary number of times, and in additional circumstances. (Abstract)
以下が可能になる
code:python
>> # *演算子、**演算子の利用方法の拡張
>> print(*1, *2, 3)
1 2 3
>> dict(**{'x': 1}, y=2, **{'z': 3})
{'x': 1, 'y': 2, 'z': 3}
code:python
>> # タプル、リスト、集合、辞書表現
>> *range(4), 4
(0, 1, 2, 3, 4)
>> *range(4), 4
0, 1, 2, 3, 4
>> {*range(4), 4}
{0, 1, 2, 3, 4}
>> {'x': 1, **{'y': 2}}
{'x': 1, 'y': 2}
なぜ提案したか(Rationale)
Current usage of the * iterable unpacking operator features unnecessary restrictions that can harm readability.
Simple examples where this is useful are print and str.format. Instead, you could be forced to write:
code:python
kwargs = dict(kw_arguments)
kwargs.update(more_arguments)
function(**kwargs)
args = list(arguments)
args.append(arg)
function(*args)
updateやappendで位置引数リストやキーワード引数リストを操作しなくてよくなる!
だいぶ読みやすくなった印象
updateやappendの代わりに、collections.ChainMapやitertools.chainを使った例も紹介
https://docs.python.org/ja/3/library/collections.html#collections.ChainMap
複数の辞書やその他のマッピングをまとめて、一つの、更新可能なビューを作成します。
https://docs.python.org/ja/3/library/itertools.html#itertools.chain
先頭の iterable の全要素を返し、次に2番目の iterable の全要素を返し、と全 iterable の要素を返すイテレータを作成します。
Disadvantages より
Whilst *elements, = iterable causes elements to be a list, elements = *iterable, causes elements to be a tuple.
code:python
>> iterable = range(3)
>> *elements, = iterable # catch-allアンパック
>> elements
0, 1, 2
>> elements = *iterable
File "<stdin>", line 1
SyntaxError: can't use starred expression here
>> f(*iterable) # tupleとして渡る(シーケンスのアンパック→タプルのパック)
(0, 1, 2)